<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function MySelector(selector, context = document) {
        if (selector.startsWith("#")) {
          // ID 选择器
          return context.getElementById(selector.slice(1));
        } else if (selector.startsWith(".")) {
          // 类名选择器
          return context.getElementsByClassName(selector.slice(1));
        } else if (/^[a-zA-Z][a-zA-Z0-9-_]*$/.test(selector)) {
          // 标签名选择器
          return context.getElementsByTagName(selector);
        } else {
          if (context.querySelector) {
            return context.querySelector(selector);
          } else {
            // 如果 querySelector 不支持，则尝试使用更基本的方法
            console.warn(
              "The context does not support querySelector. Consider using a different context or selector."
            );
            return null;
          }
        }
      }

      // 示例使用
      var singleElement = MySelector("#myId");
      var multipleElements = MySelector(".myClass");
      var tagElements = MySelector("div");
      var elementInContext = MySelector(
        "span",
        document.getElementById("someId")
      );
    </script>
  </body>
</html>
